package com.chinamsp.dydb.query;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.chinamsp.dydb.convert.ORMNameConverter;
import com.chinamsp.dydb.crud.QueryOrderType;
import com.chinamsp.dydb.util.BizUtils;

/**
 * 排序方式 构建类
 * @author shifenghu
 *
 */
public class OrderByBuilder {

	private List<OrderBy> orderBys;
	
	public OrderByBuilder() {
		orderBys = new ArrayList<>(8);
	}
	
	/**
	 * 添加 排序
	 * @param orderBies
	 * @return
	 */
	public OrderByBuilder add(OrderBy...orderBies) {
		if (orderBies != null) {
			Arrays.stream(orderBies).forEach(ob ->{
				this.orderBys.add(ob);
			});
		}
		return this;
	}
	
	/**
	 * 添加 多个 排序
	 * @param orderBies
	 * @return
	 */
	public OrderByBuilder add(List<OrderBy> orderBies) {
		if(!CollectionUtils.isEmpty(orderBies)){
			orderBies.forEach(ob -> {
				this.orderBys.add(ob);
			});
		}
		return this;
	}
	
	/**
	 * 添加一个配需方式，type = null默认是升序
	 * @param propertyName
	 * @param type
	 * @return
	 */
	public OrderByBuilder add(String propertyName, QueryOrderType type) {
		Assert.notNull(propertyName, "排序的属性不能为空");
		type = type == null ? QueryOrderType.ASC : type;
		this.orderBys.add(new OrderBy(ORMNameConverter.INSTANCE.convertToField(propertyName), type));
		return this;
	}
	
	
	/**
	 * 添加一个升序排序
	 * @param propertyName
	 * @return
	 */
	public OrderByBuilder addAsc(String propertyName) {
		return add(propertyName, QueryOrderType.ASC);
	}
	
	/**
	 * 添加一个降序
	 * @param propertyName
	 * @return
	 */
	public OrderByBuilder addDesc(String propertyName) {
		return add(propertyName, QueryOrderType.DESC);
	}
	
	/**
	 * 根据 排序类型英文添加一个排序
	 * @param propertyName
	 * @param orderTypeName 必须全大写
	 * @return
	 */
	public OrderByBuilder add(String propertyName, String orderTypeName) {
		return add(propertyName, QueryOrderType.valueOf(orderTypeName));
	}
	
	/**
	 * 获取一个排序方式
	 * @return
	 */
	public OrderBy build() {
		return BizUtils.forceOne(orderBys);
	}
	
	/**
	 * 获取 排序列表
	 * @return
	 */
	public List<OrderBy> builds(){
		return orderBys;
	}
	
	/**
	 * 生成一个 排序
	 * @param propertyName
	 * @param type
	 * @return
	 */
	public static OrderBy build(String propertyName, QueryOrderType type) {
		return newDefault().add(propertyName, type).build();
	}
	
	/**
	 * 生成一个排序
	 * @param propertyName
	 * @param orderType
	 * @return
	 */
	public static OrderBy build(String propertyName, String orderType) {
		return newDefault().add(propertyName, orderType).build();
	}
	
	/**
	 * 初始化一个默认数量的 OrderByBuilder
	 * @return
	 */
	public static OrderByBuilder newDefault() {
		return new OrderByBuilder();
	}
}
